package com.bjtang.book.service.impl;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bjtang.book.entiy.SysUser;
import com.bjtang.book.enums.SESSION;
import com.bjtang.book.myexception.DataErrorException;
import com.bjtang.book.myexception.DataOperateException;
import com.bjtang.book.service.MyService;
import com.bjtang.book.service.SysUserService;
import com.bjtang.book.util.ApplicationUtils;
import com.bjtang.book.util.RSA加密;

@Service
public class MyServiceImpl implements MyService {
	@Autowired
	private SysUserService sysUserService;

	@Override
	public SysUser getMyselfUser() {
		SysUser sysUser = sysUserService.getById(getMyselfId());
		return Optional.ofNullable(sysUser)
				.orElseThrow(() -> new DataErrorException("找不到id为:" + getMyselfId() + "的用户"));
	}

	@Override
	public SysUser updateMyselfUser(SysUser sysUser) {
		sysUser.setUserId(getMyselfId());
		if (sysUser.getPassword() != null)
			sysUser.setPassword(new RSA加密().加密(sysUser.getPassword()));

		boolean saveOrUpdate = sysUserService.saveOrUpdate(sysUser);
		if (saveOrUpdate)
			return sysUser;
		else
			throw new DataOperateException("更新失败");
	}

	@Override
	public Long getMyselfId() {
		return (Long) Optional
				.ofNullable(ApplicationUtils.getRequest().getSession().getAttribute(SESSION.USER_ID_SESSION.name()))
				.orElseThrow(() -> new DataErrorException("Id为null"));
	}

}
